package com.easy.service.impl;

import com.auth0.jwt.JWT;
import com.easy.bean.User;
import com.easy.dao.ILoginDao;
import com.easy.service.ILoginService;
import com.easy.util.DigestUtil;
import com.easy.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Primary
public class LoginImpl implements ILoginService {
    @Autowired
    ILoginDao dao;

    private boolean eqPassword(String password,String password_data){
        return password.equals(password_data);
    }

    @Override
    public String Login(User user) {
        // 1、获取数据库中的数据  byname
        List<User> list = dao.getUserByUsername(user.getUser_name());
        System.out.println(list.get(0).getUser_name());
        System.out.println(list.get(0).getDigest_password());
        System.out.println(user.getUser_name());
        System.out.println(user.getPassword());
        if (list.size() == 1) {
            User user_data = list.get(0);

            // 2、比较密码
            boolean bool = DigestUtil.decode(user.getPassword(), user_data.getDigest_password());
            System.out.println("密码匹配: " + bool);
            if (bool) {
                // 3、生成token
                String username = user_data.getUser_name();
                HashMap<String,Object> map = new HashMap();
                map.put("id",user_data.getId());
                map.put("user_name",user_data.getUser_name());
//                map.put("password",user_data.getPassword());
//                map.put("real_name",user_data.getReal_name());
//                map.put("headimage",user_data.getHead_image());
//                map.put("sex",user_data.getSex());
//                map.put("phone",user_data.getPhone());
//                map.put("birthday",user_data.getBirthday());
                map.put("role_id",user_data.getRole_id());
                String token = JWTUtil.createToken(map);
                return token;
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> decode(String token) {
        Map<String, Object> userInfo = JWT.decode(token).getClaim("userInfo").asMap();
        return userInfo;
    }

}
